package com.spark.gaea.utils;

import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.UUID;

public final class ID {
	private static final int LENGTH = 12;
	private static final String FORMAT = "yyyyMMdd";

	public static String getNativeUUID() {
		return UUID.randomUUID().toString();
	}

	public static String uuid() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	public static String[] getUUID(final int number) {
		if (number < 1) {
			return null;
		}
		final String[] ss = new String[number];
		for (int i = 0; i < number; ++i) {
			ss[i] = uuid();
		}
		return ss;
	}

	public static String base58Uuid() {
		final UUID uuid = UUID.randomUUID();
		return base58Uuid(uuid);
	}

	public static String encodeBase58Uuid(final String uuidString) {
		final UUID uuid = UUID.fromString(uuidString);
		return base58Uuid(uuid);
	}

	public static String decodeBase58Uuid(final String base58uuid) {
		final byte[] byUuid = Base58.decode(base58uuid);
		final ByteBuffer bb = ByteBuffer.wrap(byUuid);
		final UUID uuid = new UUID(bb.getLong(), bb.getLong());
		return uuid.toString();
	}

	private static String base58Uuid(final UUID uuid) {
		final ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
		bb.putLong(uuid.getMostSignificantBits());
		bb.putLong(uuid.getLeastSignificantBits());
		return Base58.encode(bb.array());
	}

	public static String gen(final Serializable id) {
		return gen(id, 12);
	}

	public static String gen(final Serializable id, int length) {
		final StringBuffer fix = new StringBuffer();
		while (length > 0) {
			fix.append('0');
			--length;
		}
		fix.append(id);
		return fix.substring(id.toString().length(), fix.length());
	}

	public static String gen(final Serializable id, final String prefix) {
		return gen(id, prefix, 12);
	}

	public static String gen(final Serializable id, final String prefix, final int length) {
		return prefix + gen(id, length);
	}

	public static String date(final Serializable id) {
		return date(id, 12);
	}

	public static String date(final Serializable id, final int length) {
		return date(id, new Date(), length);
	}

	public static String date(final Serializable id, final Date date) {
		return date(id, date, "yyyyMMdd", 12);
	}

	public static String date(final Serializable id, final Date date, final int length) {
		return date(id, date, "yyyyMMdd", length);
	}

	public static String date(final Serializable id, final Date date, final String format) {
		return date(id, date, format, 12);
	}

	public static String date(final Serializable id, final Date date, final String format, final int length) {
		return gen(id, DateUtil.format(date, format), length);
	}
}
